package com.wyl.config;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.ServletContextAware;


@Component
public class XygDataInitializer implements InitializingBean,ServletContextAware {
	private ServletContext servletContext;
	
	/*@Autowired
	private WebApplicationContext webApplicationContext;
	*/
	@Override
	public void setServletContext(ServletContext servletContext) {
		// TODO Auto-generated method stub
		this.servletContext = servletContext;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub		
		long st = System.currentTimeMillis();
		Map<String,Map<String,Object>> controllerLink = new HashMap<String,Map<String,Object>>();
		
		ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
        for (BeanDefinition beanDefinition : scanner.findCandidateComponents("com.wyl")){
        	
        	Class<?> cClass = Class.forName(beanDefinition.getBeanClassName());
        	Map<String,Object> tempMap = new HashMap<String,Object>();  

        	Object c = cClass.newInstance();
        	Field[] fields = cClass.getDeclaredFields();        	
        	for(Field f : fields){        		
        		f.setAccessible(true);
        		if(f.getType().equals(String.class) && (f.getName().lastIndexOf("_LINK")>=0 || f.getName().lastIndexOf("_ACTION")>=0))
        			tempMap.put(f.getName(), f.get(c));  
    		}        	
        	controllerLink.put(cClass.getName(), tempMap);        	
        }
        System.out.println(System.currentTimeMillis()-st);        
        servletContext.setAttribute("controllerLink",controllerLink);
	}
}